<template>
    <div class="chat-container">
        <el-card class="chat-card">
            <template #header>
                <div class="card-header">
                    <span>{{ isConsultant ? '医生' : '用户' }}</span>
                    <div v-if="connected">
                        <el-tag type="success">已连接</el-tag>
                        <span class="username">{{ isConsultant ? '医生' : '用户' }}: {{ userName }}</span>
                        <span v-if="isConsultant" class="user-count">当前用户数: {{ userCount }}</span>
                    </div>
                    <el-tag v-else type="danger">未连接</el-tag>
                </div>
            </template>

            <div class="chat-messages" ref="messagesContainer">
                <div v-for="(message, index) in messages" :key="index" class="message-item">
                    <div v-if="message.type === 'system'" class="system-message">
                        {{ message.content }}
                    </div>
                    <div v-else-if="message.type === 'user_join'" class="user-join-message">
                        {{ message.content }}
                    </div>
                    <div v-else-if="message.type === 'user_leave'" class="user-leave-message">
                        {{ message.content }}
                    </div>
                    <div v-else class="message" :class="{
                        'my-message': message.isSelf,
                        'other-message': !message.isSelf
                    }">
                        <span class="message-sender">{{ message.sender }}</span>
                        <span class="message-time">{{ formatTime(message.timestamp) }}</span>
                        <div class="message-content">{{ message.content }}</div>
                    </div>
                </div>
            </div>

            <div class="chat-input-area">
                <el-input v-model="inputMessage" :placeholder="isConsultant ? '请输入回复内容' : '请输入医疗问题'"
                    :disabled="!connected" @keyup.enter="sendMessage" clearable>
                    <template #append>
                        <el-button type="primary" :disabled="!connected || !inputMessage" @click="sendMessage"
                            :icon="Promotion">
                            发送
                        </el-button>
                    </template>
                </el-input>
            </div>
        </el-card>

        <div class="connection-controls">
            <template v-if="!connected">
                <el-input v-model="userName" :placeholder="isConsultant ? '请输入医生名称(以consultant_开头)' : '请输入用户名'"
                    class="name-input" clearable />
                <el-button type="primary" class="connect-button"
                    :disabled="!userName || (isConsultant && !userName.startsWith('consultant_'))" @click="connect">
                    {{ isConsultant ? '开始对话' : '加入对话' }}
                </el-button>

                <el-radio-group v-model="isConsultant" class="role-selector">
                    <el-radio-button :value="true">医生</el-radio-button>
                    <el-radio-button :value="false">用户</el-radio-button>
                </el-radio-group>
            </template>
            <template v-else>
                <el-button type="danger" @click="disconnect" plain>
                    {{ isConsultant ? '结束对话' : '离开对话' }}
                </el-button>
            </template>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { Promotion } from '@element-plus/icons-vue';
import { WebSocketUtil } from '../utils/WebSocketUtil';

const messages = ref([]);
const inputMessage = ref('');
const userName = ref('');
const connected = ref(false);
const userCount = ref(0);
const messagesContainer = ref(null);
const isConsultant = ref(true);

const wsUrl = 'ws://localhost:9988/WebSocketHandler';
const websocket = new WebSocketUtil(wsUrl);

const connect = () => {
    if (!userName.value.trim()) {
        ElMessage.warning('请输入用户名');
        return;
    }

    if (isConsultant.value && !userName.value.startsWith('consultant_')) {
        ElMessage.warning('医疗师名称必须以consultant_开头');
        return;
    }

    websocket.connect(userName.value);

    websocket.addOpenHandler(() => {
        connected.value = true;
        const welcomeMessage = isConsultant.value
            ? `医疗师 ${userName.value} 已上线，等待用户医疗`
            : `用户 ${userName.value} 已连接到医疗室`;
        addSystemMessage(welcomeMessage);
    });

    websocket.addMessageHandler((message) => {
        console.log('收到消息:', message);

        if (message.startsWith('[USERCOUNT]')) {
            userCount.value = parseInt(message.substring(11));
        }
        else if (message.startsWith('[USERJOIN]')) {
            const username = message.substring(10);
            addUserJoinMessage(`用户 ${username} 加入了医疗`);
        }
        else if (message.startsWith('[USERLEAVE]')) {
            const username = message.substring(11);
            addUserLeaveMessage(`用户 ${username} 离开了医疗`);
        }
        else {
            const separatorIndex = message.indexOf(':');
            if (separatorIndex > 0) {
                const sender = message.substring(0, separatorIndex);
                const content = message.substring(separatorIndex + 1);

                addMessage({
                    sender: sender,
                    content: content,
                    timestamp: Date.now(),
                    isSelf: sender === userName.value
                });
            } else {
                addSystemMessage(message);
            }
        }
    });

    websocket.addErrorHandler(() => {
        ElMessage.error('WebSocket连接出错');
        disconnect();
    });

    websocket.addCloseHandler(() => {
        connected.value = false;
        addSystemMessage(`连接已关闭`);
    });
};

const disconnect = () => {
    websocket.disconnect();
    connected.value = false;
    userCount.value = 0;
};

const sendMessage = () => {
    if (!inputMessage.value.trim()) return;

    websocket.sendMessage(inputMessage.value);
    addMessage({
        sender: userName.value,
        content: inputMessage.value,
        timestamp: Date.now(),
        isSelf: true
    });
    inputMessage.value = '';
};

const addMessage = (message) => {
    messages.value.push({
        type: 'message',
        ...message
    });
    scrollToBottom();
};

const addSystemMessage = (content) => {
    messages.value.push({
        type: 'system',
        content: content,
        timestamp: Date.now()
    });
    scrollToBottom();
};

const addUserJoinMessage = (content) => {
    messages.value.push({
        type: 'user_join',
        content: content,
        timestamp: Date.now()
    });
    scrollToBottom();
};

const addUserLeaveMessage = (content) => {
    messages.value.push({
        type: 'user_leave',
        content: content,
        timestamp: Date.now()
    });
    scrollToBottom();
};

const scrollToBottom = () => {
    nextTick(() => {
        if (messagesContainer.value) {
            messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
        }
    });
};

const formatTime = (timestamp) => {
    const date = new Date(timestamp);
    return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
};

onMounted(() => {
    scrollToBottom();
});

onUnmounted(() => {
    disconnect();
});
</script>

<style scoped>
.chat-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.chat-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
}

.username,
.user-count {
    margin-left: 10px;
    font-size: 14px;
    color: #666;
}

.chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    background-color: #f9f9f9;
    border-radius: 4px;
    margin-bottom: 10px;
}

.message-item {
    margin-bottom: 12px;
}

.system-message {
    text-align: center;
    color: #999;
    font-size: 12px;
    margin: 5px 0;
}

.user-join-message {
    text-align: center;
    color: #67C23A;
    font-size: 12px;
    margin: 5px 0;
}

.user-leave-message {
    text-align: center;
    color: #F56C6C;
    font-size: 12px;
    margin: 5px 0;
}

/* 自己发送的消息样式 */
.my-message {
    background-color: #e1f5fe;
    padding: 8px 12px;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    max-width: 70%;
    margin-left: auto;
    margin-right: 0;
    border-top-right-radius: 0;
}

/* 对方发送的消息样式 */
.other-message {
    background-color: #fff;
    padding: 8px 12px;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    max-width: 70%;
    margin-right: auto;
    margin-left: 0;
    border-top-left-radius: 0;
}

.message-sender {
    font-weight: bold;
    font-size: 13px;
    color: #333;
    display: block;
}

.message-time {
    font-size: 11px;
    color: #999;
    margin-left: 8px;
}

.message-content {
    margin-top: 4px;
    word-break: break-word;
}

.chat-input-area {
    padding: 10px;
    background-color: #fff;
    border-top: 1px solid #eee;
}

.connection-controls {
    margin-top: 20px;
    display: flex;
    gap: 10px;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
}

.name-input {
    width: 250px;
}

.connect-button {
    min-width: 120px;
}

.role-selector {
    margin-left: 20px;
}

.el-card {
    display: flex;
    flex-direction: column;
    height: 100%;
}

:deep(.el-card__body) {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    padding: 0;
}
</style>